import React, { useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Form, Input, Button, Card, message, Switch } from 'antd';
import { history } from 'umi';
import { createRole, RoleData } from '@/services/role';

const { TextArea } = Input;

const RoleCreatePage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: RoleData) => {
    setLoading(true);
    try {
      const response = await createRole(values);
      if (response.success) {
        message.success('角色创建成功');
        history.push('/role/list');
      } else {
        message.error(response.message || '角色创建失败');
      }
    } catch (error) {
      console.error('创建角色出错:', error);
      message.error('角色创建失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理返回到列表页面的函数
  const handleReturn = () => {
    history.push('/role/list');
  };

  return (
    <PageContainer
      header={{
        title: '新建角色',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '角色管理', path: '/role/list', onClick: () => handleReturn() },
            { title: '新建角色' },
          ],
        },
        onBack: () => handleReturn(),
      }}
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            status: true,
          }}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked />
          </Form.Item>

          <Form.Item
            name="description"
            label="角色描述"
            rules={[
              { max: 255, message: '描述信息不能超过255个字符' },
            ]}
          >
            <TextArea rows={4} placeholder="请输入角色描述" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              提交
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={handleReturn}
              disabled={loading}
            >
              返回
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default RoleCreatePage;
